<template>
	<div class="m-mzw-date-picker">
		<picker-view v-if="isReset" :value="pickerValue" :indicator-style="indicatorStyle" @change="bindChange" class="picker-view">
			<picker-view-column>
				<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
			</picker-view-column>
			<picker-view-column>
				<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
			</picker-view-column>
			<picker-view-column>
				<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
			</picker-view-column>
		</picker-view>
		<view class="picker-btns">
			<view class="picker-btn" @click="handleReset">重置</view>
			<view class="picker-btn bg1" @click="handleConfirm">确定</view>
		</view>
	</div>
</template>

<script>
	export default {
		name:"mzw-date-picker",
		props:{
			yearRange:{
				type: Array,
				default: () => [4,4]
			},
			defaultValue: {
				type: String,
				default: '' // 不传则默认使用当前日期
			}
		},
		data() {
			const date = new Date()
			const years = []
			const year = date.getFullYear()
			const months = []
			const month = date.getMonth() + 1
			const days = []
			const day = date.getDate()
			for (let i = 2021; i <= date.getFullYear(); i++) {
				years.push(i)
			}
			for (let i = 1; i <= 12; i++) {
				months.push(i)
			}
			for (let i = 1; i <= 31; i++) {
				days.push(i)
			}
			return {
				pickerValue:[0,0,0],
				years,
				months,
				days,
				year,
				month,
				day,
				indicatorStyle:"height:44px;font-weight: 600;background-color:rgba(246, 246, 246, 0.2);",
				isReset: true
			};
		},
		mounted() {
			this.init();
		},
		methods:{
			//初始化
			init(){
				if (this.defaultValue) {
					this.initWithDefaultValue();
				} else {
					this.initWithCurrentDate();
				}
			},
			//使用外部传入的默认值初始化
			initWithDefaultValue() {
				let targetYear = null, targetMonth = null, targetDay = null;
	
				if (typeof this.defaultValue === 'string') {
					// 格式如 "2024-01-15"
					const match = this.defaultValue.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
					if (match) {
						targetYear = parseInt(match[1], 10);
						targetMonth = parseInt(match[2], 10);
						targetDay = parseInt(match[3], 10);
					}
				}
	
				if (targetYear && targetMonth && targetDay) {
					const [before,after] = this.yearRange;
					this.createYears(targetYear - before, targetYear + after); // 可根据需求调整年份范围
					this.createMonths();
					this.createDays(targetYear, targetMonth);
	
					// 找到对应的索引
					const yearIndex = this.years.indexOf(targetYear);
					const monthIndex = this.months.indexOf(targetMonth);
					const dayIndex = this.days.indexOf(targetDay);
	
					if (yearIndex !== -1 && monthIndex !== -1 && dayIndex !== -1) {
						this.year = targetYear;
						this.month = targetMonth;
						this.day = targetDay;
						
						this.pickerValue = [yearIndex, monthIndex, dayIndex]
					} else {
						console.warn('默认值年/月/日不在可选范围内，将使用当前日期');
						this.initWithCurrentDate();
					}
				} else {
					console.warn('defaultValue 格式错误，将使用当前日期');
					this.initWithCurrentDate();
				}
			},
			//使用当前日期初始化（原有逻辑）
			initWithCurrentDate() {
				const currentDate = new Date();
				const currentYear = currentDate.getFullYear();
				const currentMonth = currentDate.getMonth() + 1;
				const currentDay = currentDate.getDate();
	
				const [before,after] = this.yearRange;
				this.createYears(currentYear - before, currentYear + after);
				this.createMonths();
				this.createDays(currentYear, currentMonth);
	
				this.year = currentYear;
				this.month = currentMonth;
				this.day = currentDay;
	
				const yearIndex = this.years.indexOf(currentYear);
				const monthIndex = this.months.indexOf(currentMonth);
				const dayIndex = this.days.indexOf(currentDay);
				this.pickerValue = [yearIndex, monthIndex, dayIndex]
			},
			//年
			createYears(before,after){
				const years = [];
				for (let i = before; i <= after; i++) {
					years.push(i);
				}
				this.years = years;
			},
			//月
			createMonths(){
				const months = [];
				for (let i = 1; i <= 12; i++) {
					months.push(i);
				}
				this.months = months;
			},
			//日
			createDays(year,month){
				const days = [];
				//获取当前月份的天数
				const daysInMonth = new Date(year, month, 0).getDate();
				for (let i = 1; i <= daysInMonth; i++) {
					days.push(i);
				}
				this.days = days;
			},
			bindChange(e){
				const val = e.detail.value;
				const yearIndex = val[0];
				const monthIndex = val[1];
				let dayIndex = val[2];
				
				this.year = this.years[yearIndex];
				this.month = this.months[monthIndex];
				this.createDays(this.year, this.month);
				
				if (!this.days[dayIndex]) {
					dayIndex = this.days.length - 1;
				}
				this.day = this.days[dayIndex];
			},
			handleReset(){
				// this.pickerValue = [0,0,0];
				this.$emit('reset');
			},
			handleConfirm(){
				// 触发change事件，向父组件传递选中的日期
				this.$emit('confirm', {
					year: this.year,
					month: this.month,
					day: this.day,
					date: `${this.year}-${this.month.toString().padStart(2, '0')}-${this.day.toString().padStart(2, '0')}`
				});
			}
		}
	}
</script>

<style lang="scss">
.m-mzw-date-picker{
	.picker-view{
		width: 100%;
		height: 220px;
		text-align: center;
		font-size: 14px;
		color: #1C274C;
		line-height: 44px;
	}
	.picker-btns{
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-top: 20rpx;
		.picker-btn{
			display: block;
			width: 335rpx;
			height: 88rpx;
			border-radius: 44rpx;
			background-color: rgba(36, 167, 206, 0.1);
			font-weight: 600;
			font-size: 32rpx;
			line-height: 88rpx;
			text-align: center;
			color: #24A7CE;
			&.bg1{
				background: linear-gradient(98.86deg, #00BBFF 0%, #5ADA7A 100%);
				color: #ffff;
			}
		}
	}
}
</style>